package server

import (
	"adai.design/jarvis/common/log"
	"net/http"
	"strings"
	"time"
)

var router = map[string]http.Handler{}

func AddService(identify string, controller http.Handler) {
	router[identify] = controller
}

type routerHTTP struct{}

func (*routerHTTP) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	request.ParseForm()
	path := strings.Split(request.URL.Path, "/")
	if len(path) > 1 {
		if h, ok := router[path[1]]; ok {
			h.ServeHTTP(response, request)
			return
		}
	}
	http.Error(response, "404 Not Found ^_^", 404)
}

func Start(end chan bool) {
	go func() {
		serveHTTP := http.Server{
			Addr:        ":6666",
			Handler:     &routerHTTP{},
			ReadTimeout: 5 * time.Second,
		}

		err := serveHTTP.ListenAndServe()
		if err != nil {
			log.Error("listen and serve: %s", err)
		}
		end <- true
	}()
}
